<template>
	<view class="settings-container">
		<!-- 渐变背景 -->
		<view class="gradient-bg"></view>
		
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-content">
				<view class="navbar-left" @click="goBack">
					<text class="back-icon">‹</text>
				</view>
				<text class="navbar-title">设置</text>
			</view>
		</view>
		
		<!-- 设置列表 -->
		<view class="settings-section">
			<!-- 通知设置 -->
			<view class="section-card">
				<view class="section-title">通知设置</view>
				
				<view class="setting-item">
					<view class="item-left">
						<view class="item-icon notification">
							<text class="icon-text">🔔</text>
						</view>
						<view class="item-info">
							<text class="item-title">推送通知</text>
							<text class="item-desc" :class="{ 'permission-status': true, 'granted': settings.notifications, 'denied': !settings.notifications }">
								{{ settings.notifications ? '已授权 · 接收重要备忘录提醒' : '未授权 · 需要开启通知权限' }}
							</text>
						</view>
					</view>
					<switch 
						:checked="settings.notifications" 
						@change="updateSetting('notifications', $event.detail.value)"
						color="#667eea"
					/>
				</view>
				
				<view class="setting-item">
					<view class="item-left">
						<view class="item-icon sound">
							<text class="icon-text">🔊</text>
						</view>
						<view class="item-info">
							<text class="item-title">声音提醒</text>
							<text class="item-desc">通知时播放提示音</text>
						</view>
					</view>
					<switch 
						:checked="settings.soundEnabled" 
						@change="updateSetting('soundEnabled', $event.detail.value)"
						color="#667eea"
					/>
				</view>
				

			</view>
			
			<!-- 数据设置 -->
			<view class="section-card">
				<view class="section-title">数据设置</view>
				
				<view class="setting-item">
					<view class="item-left">
						<view class="item-icon auto-backup">
							<text class="icon-text">☁️</text>
						</view>
						<view class="item-info">
							<text class="item-title">自动备份</text>
							<text class="item-desc">定期自动备份数据</text>
						</view>
					</view>
					<switch 
						:checked="settings.autoBackup" 
						@change="updateSetting('autoBackup', $event.detail.value)"
						color="#667eea"
					/>
				</view>
				
				<view class="setting-item" @click="showBackupIntervalPicker">
					<view class="item-left">
						<view class="item-icon frequency">
							<text class="icon-text">⏱️</text>
						</view>
						<view class="item-info">
							<text class="item-title">备份频率</text>
							<text class="item-desc">{{ backupIntervalLabels[settings.backupInterval] }}</text>
						</view>
					</view>
					<text class="item-arrow">›</text>
				</view>
			</view>
		</view>
		
		<!-- 备份频率选择弹窗 -->
		<view class="modal-overlay" v-if="showBackupPicker" @click="hideBackupIntervalPicker">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">备份频率</text>
					<view class="close-btn" @click="hideBackupIntervalPicker">
						<text class="close-icon">×</text>
					</view>
				</view>
				<view class="choice-list">
					<view 
						class="choice-item" 
						v-for="(item, index) in backupIntervalOptions" 
						:key="index"
						:class="{ active: settings.backupInterval === index }"
						@click="confirmBackupInterval(index)"
					>
						<text class="choice-name">{{ item }}</text>
						<view class="choice-check" v-if="settings.backupInterval === index">
							<text class="check-icon">✓</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
// 通知管理器
const notificationManager = {
	// 检查通知权限
	async checkPermission() {
		return new Promise((resolve) => {
			// #ifdef APP-PLUS
			try {
				const main = plus.android.runtimeMainActivity();
				const NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
				
				if (NotificationManagerCompat) {
					const areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
					resolve(areNotificationsEnabled);
				} else {
					resolve(true); // 兼容旧版本
				}
			} catch (error) {
				console.error('检查通知权限失败:', error);
				resolve(false);
			}
			// #endif
			
			// #ifdef H5
			if ('Notification' in window) {
				resolve(Notification.permission === 'granted');
			} else {
				resolve(false);
			}
			// #endif
			
			// #ifdef MP
			resolve(true); // 小程序默认支持
			// #endif
		});
	},

	// 请求通知权限
	async requestPermission() {
		return new Promise((resolve) => {
			// #ifdef APP-PLUS
			// 引导用户去设置页面
			uni.showModal({
				title: '需要通知权限',
				content: '为了及时提醒您重要的备忘录，需要开启通知权限。请在系统设置中允许"小何备忘录"发送通知。',
				confirmText: '去设置',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						this.openAppSettings();
					}
					resolve(false); // 需要用户手动开启
				}
			});
			// #endif
			
			// #ifdef H5
			if ('Notification' in window) {
				if (Notification.permission === 'granted') {
					resolve(true);
				} else if (Notification.permission !== 'denied') {
					Notification.requestPermission().then(permission => {
						resolve(permission === 'granted');
					});
				} else {
					resolve(false);
				}
			} else {
				resolve(false);
			}
			// #endif
			
			// #ifdef MP
			uni.requestSubscribeMessage({
				tmplIds: [], // 小程序模板ID
				success: () => resolve(true),
				fail: () => resolve(false)
			});
			// #endif
		});
	},

	// 打开应用设置
	openAppSettings() {
		// #ifdef APP-PLUS
		try {
			const Intent = plus.android.importClass("android.content.Intent");
			const Settings = plus.android.importClass("android.provider.Settings");
			const Uri = plus.android.importClass("android.net.Uri");
			const main = plus.android.runtimeMainActivity();
			
			const intent = new Intent();
			intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
			const uri = Uri.fromParts("package", main.getPackageName(), null);
			intent.setData(uri);
			main.startActivity(intent);
		} catch (error) {
			console.error('打开设置失败:', error);
		}
		// #endif
	},

	// 发送本地通知
	sendLocalNotification(options = {}) {
		const defaultOptions = {
			title: '备忘录提醒',
			content: '您有新的备忘录提醒',
			sound: true,
			vibrate: true
		};
		
		const finalOptions = { ...defaultOptions, ...options };
		
		// #ifdef APP-PLUS
		try {
			// 根据声音设置选择提示音
			let soundOption = 'none';
			if (finalOptions.sound) {
				soundOption = 'system'; // 使用系统默认通知音
			}
			
			const notification = {
				title: finalOptions.title,
				content: finalOptions.content,
				when: finalOptions.when || new Date(),
				sound: soundOption,
				cover: false
			};
			
			plus.push.createMessage(notification.content, JSON.stringify(notification), {
				success: () => {
					console.log('本地通知创建成功，声音:', soundOption);
					
					// 如果开启了声音，还可以播放额外的提示音
					if (finalOptions.sound) {
						this.playNotificationSound();
					}
				},
				fail: (err) => {
					console.error('本地通知创建失败:', err);
				}
			});
		} catch (error) {
			console.error('发送本地通知失败:', error);
		}
		// #endif
		
		// #ifdef H5
		if ('Notification' in window && Notification.permission === 'granted') {
			const notification = new Notification(finalOptions.title, {
				body: finalOptions.content,
				icon: '/static/logo.png',
				requireInteraction: true,
				silent: !finalOptions.sound // H5中控制是否静音
			});
			
			// H5环境中播放自定义声音
			if (finalOptions.sound) {
				this.playNotificationSound();
			}
		}
		// #endif
	},

	// 播放通知提示音
	playNotificationSound() {
		// #ifdef APP-PLUS
		try {
			// 播放系统提示音
			plus.device.beep(1); // 播放1次系统蜂鸣音
		} catch (error) {
			console.error('播放提示音失败:', error);
		}
		// #endif
		
		// #ifdef H5
		try {
			// 创建音频上下文播放提示音
			const audioContext = new (window.AudioContext || window.webkitAudioContext)();
			const oscillator = audioContext.createOscillator();
			const gainNode = audioContext.createGain();
			
			oscillator.connect(gainNode);
			gainNode.connect(audioContext.destination);
			
			oscillator.frequency.value = 800; // 800Hz频率
			gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
			gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
			
			oscillator.start(audioContext.currentTime);
			oscillator.stop(audioContext.currentTime + 0.5);
		} catch (error) {
			console.log('H5环境播放提示音失败:', error);
		}
		// #endif
	},

	// 设置每日提醒
	scheduleDailyReminder(soundEnabled = true) {
		// 先清除之前的提醒设置
		this.clearDailyReminder();
		
		// 计算下次晚上8点的时间
		const now = new Date();
		const reminderTime = new Date();
		reminderTime.setHours(20, 0, 0, 0); // 晚上8点
		
		// 如果今天的8点已过，设置明天的8点
		if (reminderTime <= now) {
			reminderTime.setDate(reminderTime.getDate() + 1);
		}
		
		// 设置本地通知
		// #ifdef APP-PLUS
		try {
			const soundOption = soundEnabled ? 'system' : 'none';
			
			plus.push.createMessage('记得查看今天的备忘录待办事项哦！📝', JSON.stringify({
				title: '备忘录提醒',
				content: '记得查看今天的备忘录待办事项哦！📝',
				when: reminderTime,
				sound: soundOption,
				cover: false
			}), {
				success: () => {
					console.log('每日提醒设置成功:', reminderTime, '声音:', soundOption);
					
					// 保存提醒设置到本地，记录设置日期
					uni.setStorageSync('daily_reminder_set', {
						time: reminderTime.getTime(),
						enabled: true,
						soundEnabled: soundEnabled,
						setDate: new Date().toDateString() // 记录设置的日期
					});
				},
				fail: (err) => {
					console.error('每日提醒设置失败:', err);
				}
			});
		} catch (error) {
			console.error('设置每日提醒失败:', error);
		}
		// #endif
		
		// #ifdef H5
		// H5环境使用Web Notification API
		if ('Notification' in window && Notification.permission === 'granted') {
			const delay = reminderTime.getTime() - now.getTime();
			setTimeout(() => {
				const notification = new Notification('📝 备忘录提醒', {
					body: '记得查看今天的备忘录待办事项哦！',
					icon: '/static/logo.png',
					requireInteraction: true,
					silent: !soundEnabled
				});
				
				// 播放自定义提示音
				if (soundEnabled) {
					this.playNotificationSound();
				}
			}, delay);
			
			// H5环境也保存设置记录
			uni.setStorageSync('daily_reminder_set', {
				time: reminderTime.getTime(),
				enabled: true,
				soundEnabled: soundEnabled,
				setDate: new Date().toDateString()
			});
		}
		// #endif
		
		console.log('每日提醒已设置，下次提醒时间:', reminderTime, '声音开启:', soundEnabled);
	},

	// 清除定时提醒
	clearDailyReminder() {
		// #ifdef APP-PLUS
		try {
			plus.push.clear();
			console.log('已清除所有通知');
		} catch (error) {
			console.error('清除通知失败:', error);
		}
		// #endif
	}
};

export default {
	data() {
		return {
			settings: {
				notifications: false, // 默认关闭，需要检查权限
				soundEnabled: true,
				autoBackup: true,
				backupInterval: 1
			},
			showBackupPicker: false,
			backupIntervalOptions: ['每天', '每周', '每月'],
			backupIntervalLabels: {
				0: '每天',
				1: '每周',
				2: '每月'
			},
			isCheckingPermission: false
		}
	},
	async onLoad() {
		this.loadSettings();
		await this.checkNotificationPermission();
	},
	onShow() {
		// 页面显示时重新检查权限状态
		setTimeout(() => {
			this.checkNotificationPermission();
		}, 500);
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		
		loadSettings() {
			try {
				const savedSettings = uni.getStorageSync('app_settings')
				if (savedSettings) {
					this.settings = { ...this.settings, ...savedSettings }
				}
			} catch (error) {
				console.error('加载设置失败:', error)
			}
		},
		
		async updateSetting(key, value) {
			// 特殊处理通知权限
			if (key === 'notifications') {
				await this.handleNotificationSetting(value);
				return;
			}
			
			// 特殊处理声音设置
			if (key === 'soundEnabled') {
				this.settings[key] = value;
				this.saveSettings();
				
				// 如果通知已开启，重新设置每日提醒以应用新的声音设置
				if (this.settings.notifications) {
					notificationManager.scheduleDailyReminder(value);
					uni.showToast({
						title: value ? '声音提醒已开启' : '声音提醒已关闭',
						icon: 'success',
						duration: 1500
					});
				}
				return;
			}
			
			this.settings[key] = value;
			this.saveSettings();
		},
		
		// 检查通知权限状态
		async checkNotificationPermission() {
			if (this.isCheckingPermission) return;
			
			this.isCheckingPermission = true;
			try {
				const hasPermission = await notificationManager.checkPermission();
				this.settings.notifications = hasPermission;
				console.log('通知权限状态:', hasPermission);
			} catch (error) {
				console.error('检查权限失败:', error);
				this.settings.notifications = false;
			}
			this.isCheckingPermission = false;
		},
		
		// 处理通知设置
		async handleNotificationSetting(value) {
			if (value) {
				// 用户想要开启通知，检查权限
				const hasPermission = await notificationManager.checkPermission();
				
				if (hasPermission) {
					// 有权限，直接开启
					this.settings.notifications = true;
					this.saveSettings();
					
					// 启动每日提醒，传入声音设置
					notificationManager.scheduleDailyReminder(this.settings.soundEnabled);
					
					uni.showToast({
						title: '通知已开启',
						icon: 'success'
					});
				} else {
					// 没有权限，引导用户开启
					this.settings.notifications = false;
					await notificationManager.requestPermission();
					
					uni.showToast({
						title: '请先开启通知权限',
						icon: 'none',
						duration: 2000
					});
				}
			} else {
				// 关闭通知
				this.settings.notifications = false;
				this.saveSettings();
				
				// 清除定时提醒
				notificationManager.clearDailyReminder();
				
				uni.showToast({
					title: '通知已关闭',
					icon: 'success'
				});
			}
		},
		
		saveSettings() {
			try {
				uni.setStorageSync('app_settings', this.settings)
				uni.showToast({
					title: '设置已保存',
					icon: 'success',
					duration: 1000
				})
			} catch (error) {
				console.error('保存设置失败:', error)
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			}
		},
		
		showBackupIntervalPicker() {
			this.showBackupPicker = true
		},
		
		hideBackupIntervalPicker() {
			this.showBackupPicker = false
		},
		
		confirmBackupInterval(index) {
			this.updateSetting('backupInterval', index)
			this.showBackupPicker = false
		},
		

	}
}
</script>

<style lang="scss" scoped>
.settings-container {
	width: 100%;
	min-height: 100vh;
	position: relative;
	background: #f8f9fa;
	color: #333333;
}

.gradient-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: linear-gradient(135deg, #a6c0fe 0%, #f68084 100%);
	z-index: 0;
}

.custom-navbar {
	position: relative;
	z-index: 1;
	height: 88rpx;
	margin-top: var(--status-bar-height);
	background: transparent;
	padding-top: 60rpx;
}

.navbar-content {
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
}

.navbar-left {
	width: 80rpx;
	height: 60rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
}

.navbar-left:active {
	background: rgba(255, 255, 255, 0.3);
	transform: scale(0.95);
}

.back-icon {
	font-size: 36rpx;
	color: #fff;
	font-weight: bold;
}

.navbar-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #fff;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.settings-section {
	position: relative;
	z-index: 1;
	padding: 60rpx 30rpx 40rpx;
}

.section-card {
	background: rgba(255, 255, 255, 1);
	border-radius: 30rpx;
	padding: 40rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.1);
	border: 1rpx solid #e5e5e5;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 30rpx;
}

.setting-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
	transition: all 0.3s ease;
}

.setting-item:last-child {
	border-bottom: none;
}

.setting-item:active {
	background: rgba(166, 192, 254, 0.1);
	border-radius: 16rpx;
	margin: 0 -20rpx;
	padding: 30rpx 20rpx;
}

.item-left {
	display: flex;
	align-items: center;
	flex: 1;
}

.item-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 24rpx;
	
	&.notification {
		background: linear-gradient(135deg, #ff9500 0%, #ffad33 100%);
	}
	
	&.sound {
		background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
	}
	
	&.auto-backup {
		background: linear-gradient(135deg, #fd79a8 0%, #fdcb6e 100%);
	}
	
	&.frequency {
		background: linear-gradient(135deg, #e17055 0%, #74b9ff 100%);
	}
	

	

}

.icon-text {
	font-size: 32rpx;
}

.item-info {
	flex: 1;
}

.item-title {
	display: block;
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 8rpx;
}

.item-desc {
	display: block;
	font-size: 26rpx;
	color: #666;
	opacity: 0.7;
	
	&.permission-status {
		font-weight: 500;
		
		&.granted {
			color: #00b894;
			opacity: 1;
		}
		
		&.denied {
			color: #e74c3c;
			opacity: 1;
		}
	}
}

.item-arrow {
	font-size: 36rpx;
	color: #ccc;
	margin-left: 20rpx;
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 60rpx;
}

.modal-content {
	background: rgba(255, 255, 255, 1);
	border-radius: 30rpx;
	width: 100%;
	max-width: 600rpx;
	max-height: 80vh;
	overflow: hidden;
	animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
	from {
		opacity: 0;
		transform: scale(0.9) translateY(50rpx);
	}
	to {
		opacity: 1;
		transform: scale(1) translateY(0);
	}
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.close-btn {
	width: 60rpx;
	height: 60rpx;
	border-radius: 30rpx;
	background: #f5f5f5;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
}

.close-btn:active {
	background: #e0e0e0;
	transform: scale(0.95);
}

.close-icon {
	font-size: 36rpx;
	color: #666;
	font-weight: bold;
}

.choice-list {
	padding: 20rpx 0;
}

.choice-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx 40rpx;
	transition: all 0.3s ease;
	
	&:active {
		background: rgba(166, 192, 254, 0.1);
	}
	
	&.active {
		background: rgba(166, 192, 254, 0.15);
	}
}

.choice-name {
	font-size: 30rpx;
	color: #333;
	font-weight: 500;
}

.choice-check {
	width: 40rpx;
	height: 40rpx;
	border-radius: 20rpx;
	background: linear-gradient(135deg, #a6c0fe 0%, #f68084 100%);
	display: flex;
	align-items: center;
	justify-content: center;
}

.check-icon {
	font-size: 24rpx;
	color: #fff;
	font-weight: bold;
}
</style> 